package br.com.androidblog.rss;

import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;

import org.xml.sax.XMLReader;

import dalvik.system.TemporaryDirectory;

import android.content.Context;
import android.content.Intent;
import br.com.androidblog.model.ItemBlogController;

public class RSSReader {

	public final String RSSFEEDOFCHOICE = "http://feeds.feedburner.com/androidblog_br";

	public final String tag = "Channel";
	private RSSFeed feed = null;

	/** Called when the activity is first created. 
	 * @throws Exception */

	public RSSReader(Context context) throws Exception {
		
		feed = getFeed(RSSFEEDOFCHOICE);
		List lista= feed.getAllItems();
		Iterator iterator = lista.iterator();
		ItemBlogController ibc = new ItemBlogController(context);
		ibc.deleteElements(context);
		ibc.getConnection().close();
		while (iterator.hasNext()){
			RSSItem coluna = (RSSItem) iterator.next();
			Log.i("androidblog", "Descricao = " + coluna.getDescription());
			Log.i("androidblog", "Link 		= " + coluna.getLink());
			Log.i("androidblog", "Titulo 	= " + coluna.getTitle());
			
			HashMap<String, String> hm = new HashMap<String, String>();
			hm.put("titulo", coluna.getTitle());
			hm.put("url", coluna.getTitle());
			hm.put("conteudo", coluna.getDescription());
			ibc.insertCurso(hm, "blog", context);
		}
	}

	private RSSFeed getFeed(String urlToRssFeed) {
		try {
			// setup the url
			URL url = new URL(urlToRssFeed);

			// create the factory
			SAXParserFactory factory = SAXParserFactory.newInstance();
			// create a parser
			SAXParser parser = factory.newSAXParser();

			// create the reader (scanner)
			XMLReader xmlreader = parser.getXMLReader();
			// instantiate our handler
			RSSHandler theRssHandler = new RSSHandler();
			// assign our handler
			xmlreader.setContentHandler(theRssHandler);
			// get our data via the url class
			InputSource is = new InputSource(url.openStream());
			// perform the synchronous parse
			xmlreader.parse(is);
			// get the results - should be a fully populated RSSFeed instance,
			// or null on error
			return theRssHandler.getFeed();
		} catch (Exception ee) {
			Log.e(tag, ee.getLocalizedMessage());
			Log.e(tag, ee.getMessage());
			// if we have a problem, simply return null
			return null;
		}
	}

	private void UpdateDisplay() {

//		ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,
//				android.R.layout.simple_list_item_1, feed.getAllItems());

	}

}